var express = require('express');
var router = express.Router();
var mysql = require('./mysqlConfig');
// var redis = require('./redisServer');
var register = require('babel-core/register')


/* GET home page. */

//处理连接数据库
const connectionMysql = (sql) => {
    return new Promise(function(resolve, reject) {
        mysql.getConnection(function(err, connection) {
            if (err) {
                reject(err)
            } else {
                resolve(sqlSever(connection, sql))
            }
        });
    });
}
//处理sql语句
const sqlSever = (connection, sql) => {
    return new Promise(function(resolve, reject) {
        connection.query(sql, function(err, rows, fields) {
            if (err) {

                reject(err);
            } else {
                console.log(err)
                resolve(rows);
            }
        })
    });
}

//使用asyncFun对异步处理
router.get('/getList', function(req, res, next) {
    var sql = 'select title from test';
    connectionMysql(sql)
        .then((result) => {
            var json = {
                code: 200,
                data: result
            }
            res.send(json);
        })
        .catch((reason) => {
            var json = {
                code: 400,
                data: "错了"
            }
            res.send(json);
        });
});

module.exports = router;